package com.wjjun.base.data.net;

import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.luck.picture.lib.rxbus2.RxBus;
import com.qingmi.farmer.R;
import com.qingmi.farmer.data.ResCodes;
import com.qingmi.farmer.data.UserData;
import com.qingmi.farmer.event.UserLoginChangeEvent;
import com.qingmi.farmer.ui.login.LoginActivity;
import com.wjjun.base.App;
import com.wjjun.basemvpvm.data.net.filter.BaseResponseFilter;
import com.wjjun.basemvpvm.data.response.BaseResponse;

/**
 * author Wjjun
 * Created 2018/3/22.
 */

public class TokenFilter implements BaseResponseFilter {

    private App app;

    public TokenFilter(App app) {
        this.app = app;
    }

    @Override
    public boolean onFilter(BaseResponse response) {
        if (response.isSuccess()) {
            return false;
        } else if (response.getErrorCode() == ResCodes.TOKEN_INVALID) {
            ToastUtils.showLong(R.string.error_token_invalid);
            UserData.getInstance().setUserInfo(null);
            UserData.getInstance().setToken("");
            RxBus.getDefault().post(new UserLoginChangeEvent());

            if (ActivityUtils.getTopActivity().getClass() == LoginActivity.class) {
                return true;
            }
            LoginActivity.start(app, false);
            ActivityUtils.finishOtherActivities(LoginActivity.class);
            return true;
        }
        return false;
    }
}
